<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input clearable class="filter-item" v-model="indexParam.queryDto.kw" placeholder="请输入博客名" @keyup.enter.native="handleFind"></el-input>

      <el-select class="filter-item" style="width:130px" v-model="indexParam.queryDto.blogType" filterable clearable placeholder="请输入分类名" @keyup.enter.native="handleFind">
        <el-option v-for="item in blogTypes" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select class="filter-item" style="width:130px" v-model="indexParam.queryDto.tagId" filterable clearable placeholder="请输入标签名" @keyup.enter.native="handleFind">
        <el-option v-for="item in blogTagList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select class="filter-item" v-model="indexParam.queryDto.isEssence" clearable placeholder="推荐等级" style="width:110px">
        <el-option :key="1" label="推荐" :value="1"></el-option>
        <el-option :key="0" label="普通" :value="0"></el-option>
      </el-select>

      <el-select class="filter-item" v-model="indexParam.queryDto.online" clearable placeholder="是否发布" style="width:110px">
        <el-option :key="1" label="发布" :value="1"></el-option>
        <el-option :key="0" label="下线" :value="0"></el-option>
      </el-select>

      <el-select class="filter-item" v-model="indexParam.queryDto.originalKeyword" clearable placeholder="是否原创" style="width:110px">
<!--        <el-option v-for="item in sysOriginalStatus.sysDictDataList" :key="item.uid" :label="item.dictLabel" :value="item.dictValue"></el-option>-->
      </el-select>

      <el-select class="filter-item" v-model="indexParam.queryDto.isTop" clearable placeholder="是否置顶" style="width:110px">
        <el-option :key="1" label="置顶" :value="1"></el-option>
        <el-option :key="0" label="普通" :value="0"></el-option>
      </el-select>

      <el-button type="primary" @click="handleFind" icon="el-icon-search">查找</el-button>
      <el-button type="success" @click="handleAdd" icon="el-icon-edit">添加</el-button>
      <!-- <el-button type="info" @click="handleUpload" icon="el-icon-star-on">上传</el-button> -->
      <el-button type="warning" @click="handleDownload" icon="el-icon-s-flag">导出</el-button>
      <el-button type="danger" @click="handleDeleteBatch" icon="el-icon-delete">删除</el-button>
    </div>

    <el-table :data="tableData" v-loading="Loading" style="width: 100%" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection"></el-table-column>

      <el-table-column label="序号" width="60" align="center">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column label="封面" width="130" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.pic" :preview-src-list="[scope.row.pic]" fit="cover" style="height: 65px;"></el-image>
        </template>
      </el-table-column>

      <el-table-column label="标题" min-width="160" align="center">
        <template slot-scope="scope">
          <span @click="gotoBlogInfo(scope.row)" style="cursor:pointer;">{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="作者" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="是否原创" align="center">
        <template slot-scope="scope">
          <el-tag  type="success" size="small" effect="plain">暂未开发</el-tag>
<!--          <el-tag v-if="scope.row.isOriginal==1" type="success" size="small" effect="plain">原创</el-tag>-->
<!--          <el-tag v-if="scope.row.isOriginal==0" type="info" size="small" effect="plain">转载</el-tag>-->
        </template>
      </el-table-column>

      <el-table-column label="分类" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.typeId">{{ getBlogType(scope.row.typeId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="标签" min-width="160" align="center">
        <template slot-scope="scope">
          <el-tag size="small" effect="plain" style="margin-left: 1px" type="info" :key="index" v-for="(item, index) in scope.row.tagNameList">{{item}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="推荐等级" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isEssence==0" type="info" size="small" effect="plain">正常</el-tag>
<!--          <el-tag v-if="scope.row.level==1" type="danger" size="small" effect="plain">聚焦</el-tag>-->
          <el-tag v-if="scope.row.isEssence==1" type="warning" size="small" effect="plain">推荐文章</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="点击数" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.readCount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="开启评论" align="center">
        <template slot-scope="scope">
          <template>
            <el-tag type="success" size="small" effect="plain">暂未开发</el-tag>
<!--            <el-tag v-if="scope.row.startComment==1" type="success" size="small" effect="plain">开启</el-tag>-->
<!--            <el-tag v-if="scope.row.startComment==0" type="info" size="small" effect="plain">关闭</el-tag>-->
          </template>
        </template>
      </el-table-column>

      <el-table-column label="发布状态" align="center">
        <template slot-scope="scope">
          <template>
            <el-tag v-if="scope.row.online==1" type="success" size="small" effect="plain">发布</el-tag>
            <el-tag v-if="scope.row.online==0" type="info" size="small" effect="plain">下架</el-tag>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="是否置顶" align="center">
        <template slot-scope="scope">
          <template>
            <el-tag v-if="scope.row.isTop==1" type="danger" size="small" effect="plain">是</el-tag>
            <el-tag v-if="scope.row.isTop==0" type="info" size="small" effect="plain">否</el-tag>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" min-width="160" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="修改时间" min-width="160" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" min-width="160" align="center">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
          <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="block">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog v-if="dialogFormVisible" :title="title" :visible.sync="dialogFormVisible" :before-close="beforeHandleDialogClose" fullscreen>
      <el-form :model="form" :rules="rules" ref="form">

        <el-form-item label="封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8084/upload"
            :show-file-list="false"
            :on-preview="handleAvatar"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.pic" :src="form.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
              <el-input v-model="form.title" auto-complete="off" maxlength=30 show-word-limit></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="分类" :label-width="formLabelWidth" prop="blogSortUid">
              <el-select v-model="form.typeId" placeholder="请选择" style="width:100%">
                <el-option v-for="item in blogTypes" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="标签" :label-width="formLabelWidth" prop="blogTag">
              <el-select v-model="form.tagIdList" :multiple-limit="3" filterable clearable multiple placeholder="请选择" style="width:100%">
                <el-option v-for="item in blogTagList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="等级" :label-width="formLabelWidth" prop="level">
              <el-select v-model="form.isEssence" placeholder="请选择" style="width:100%">
                <el-option key="1" label="精华" :value="1"></el-option>
                <el-option key="0" label="普通" :value="0"></el-option>
<!--                <el-option v-for="item in sysRecommendLevel.sysDictDataList" :key="item.uid" :label="item.dictLabel" :value="item.dictValue"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input v-model="form.shortContext" auto-complete="off"></el-input>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item label="发布" :label-width="formLabelWidth" prop="isPublish">
              <el-radio-group v-model="form.online" size="small">
                <el-radio-button  key="1" label="1" border>上线</el-radio-button>
                <el-radio-button  key="0" label="0" border>下线</el-radio-button>
<!--                <el-radio-button v-for="item in sysPublishStatus.sysDictDataList" :key="item.uid" :label="item.dictValue" border>{{item.dictLabel}}</el-radio-button>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="原创" :label-width="formLabelWidth" prop="isOriginal">
              <el-radio-group v-model="form.isOriginal" size="small">
                <el-radio-button key="1" label="1" border>原创</el-radio-button>
                <el-radio-button key="0" label="0" border>转载</el-radio-button>
<!--                <el-radio-button v-for="item in sysOriginalStatus.sysDictDataList" :key="item.uid" :label="item.dictValue" border>{{item.dictLabel}}</el-radio-button>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="评论" :label-width="formLabelWidth" prop="startComment">
              <el-radio-group v-model="form.startComment" size="small">
                <el-radio-button key="1" label="1" border>开启</el-radio-button>
                <el-radio-button key="0" label="0" border>关闭</el-radio-button>
<!--                <el-radio-button v-for="item in sysCommentSwitch.sysDictDataList" :key="item.uid" :label="item.dictValue" border>{{item.dictLabel}}</el-radio-button>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="置顶" :label-width="formLabelWidth" prop="startComment">
              <el-radio-group v-model="form.isTop" size="small">
                <el-radio-button key="1" label="1" border>置顶</el-radio-button>
                <el-radio-button key="0" label="0" border>普通</el-radio-button>
<!--                <el-radio-button v-for="item in sysTopStatus.sysDictDataList" :key="item.uid" :label="item.dictValue" border>{{item.dictLabel}}</el-radio-button>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="版权说明" :label-width="formLabelWidth" prop="copyright">
          <el-input v-model="form.copyright" auto-complete="off" maxlength=100 show-word-limit></el-input>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="作者" :label-width="formLabelWidth" v-if="form.isOriginal==0" prop="author">
              <el-input v-model="form.author" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="文章出处" :label-width="formLabelWidth" v-if="form.isOriginal==0">
              <el-input v-model="form.articlesPart" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="内容" :label-width="formLabelWidth" prop="blogContent">
          <div ref="toastUIEditor"></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="beforeHandleDialogClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="本地博客上传" :visible.sync="localUploadVisible">
      <div class="tipBox">
        <div class="tip">导入须知</div>
        <div class="tipItem">1）如果你的Markdown文档里面的图片是本地，需要选择本地图片，然后提交到图片服务器</div>
        <div class="tipItem">2）含有本地图片一定需要提前上传图片，否者会出现图片无法替换的问题</div>
        <div class="tipItem">3）如果你的Markdown文档里面的图片不是本地，直接选择博客文件上传即可</div>
        <div class="tipItem">4）目前支持Markdown文件批量上传，步骤是先提交所有图片，在提交全部的博客文件</div>
        <div class="tipItem">5）因为网络或者服务器性能等不可抗拒的原因，因此不推荐一次上传太多</div>
      </div>

      <!-- <el-upload class="upload-demo2" ref="uploadPicture" name="filedatas" :data="otherData" :action="uploadPictureHost" :auto-upload="false" multiple>
        <el-button slot="trigger" size="small" type="primary">选取本地图片</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitPictureUpload">提交到图片服务器</el-button>
      </el-upload> -->

      <!-- <el-upload
        class="upload-demo"
        ref="uploadFile"
        name="filedatas"
        :headers="importHeaders"
        :action="uploadAdminHost"
        :auto-upload="false"
        multiple
      >
        <el-button slot="trigger" size="small" type="primary">选取博客文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click>提交到服务器</el-button>
      </el-upload>-->
    </el-dialog>
    <!-- Element的z-index（默认值：2000） -->
  </div>
</template>
<script>
import {
  getBlogList,
  getContent,
  deleteBlog,
  deleteBatchBlog,
  addBlog,
  editBlog
} from "@/api/blog";
import { getToken } from "@/utils/auth";
import { getTagList } from "@/api/tag";
import { getBlogSortList } from "@/api/blogSort";
import { getListByDictTypeList } from "@/api/sysDictData";
//toast-ui
// import 'codemirror/lib/codemirror.css';
// import '@toast-ui/editor/dist/toastui-editor.css';
// import { Editor } from '@toast-ui/vue-editor';
// import "@toast-ui/editor/dist/i18n/zh-cn";

import Editor from '@toast-ui/editor';
import 'codemirror/lib/codemirror.css'; // Editor's Dependency Style
import '@toast-ui/editor/dist/toastui-editor.css'; // Editor's Style
// import colorSyntax from '@toast-ui/editor-plugin-color-syntax';
// import 'tui-color-picker/dist/tui-color-picker.css';
import "@toast-ui/editor/dist/i18n/zh-cn";
import { uploadFile, addPicture } from "@/api/picture";
import Cookies from 'js-cookie'
export default {
  components: {
    // ChoosePhoto,
    // Editor,
  },
  data() {
    //自定义校验
    const validatefile = (rule, value, callback) => {
      if (this.form.titlePicUids === null || this.form.titlePicUids === "") {
        return callback(new Error("标题图不能为空"));
      } else {
        callback();
      }
    };
    const validateTags = (rule, value, callback) => {
      if (this.form.tagIdList.length <= 0) {
        return callback(new Error("标签不能为空"));
      } else {
        callback();
      }
    };
    const validateContent = (rule, value, callback) => {
      if (this.editor.getMarkdown().trim() === "") {
        return callback(new Error("博客内容不能为空"));
      } else {
        callback();
      }
    };
    return {
      fileList:[],
      // editorText: "This is initialValue.",
      // editorOptions: {
      //   minHeight: "200px",
      //   language: "zh-CN",
      //   useCommandShortcut: true,
      //   useDefaultHTMLSanitizer: true,
      //   usageStatistics: false,
      //   hideModeSwitch: true,
      // },
      showCutter: false, // 是否显示头像裁剪组件
      Loading: true,
      VUE_APP_WEB_URL: process.env.VUE_APP_WEB_URL,
      VUE_APP_IMAGE_URL: process.env.VUE_APP_IMAGE_URL,
      multipleSelection: [], //多选，用于批量删除
      loading: false, //搜索框加载状态
      currentPage: 0,
      pageSize: 10,
      total: 0, //总数量
      formLabelWidth: "60px",
      dialogFormVisible: false,
      localUploadVisible: false,
      title: "添加博客",
      isEditForm: false, //判断是新增还是编辑
      tableData: [],
      form: {
        id: null,
        title: null,
        pic: null,
        userId: null,
        typeId: null,
        tagIdList: [],
        tagIds: null,
        isEssence: null,
        isTop: null,
        online: null,
        isOriginal: null,
        startComment: null,
        author: null,
        articlesPart: null,
        shortContext: null,
        blogContent: null,
        copyright: null
      },
      blogTagList: [],
      blogTypes: [],
      indexParam: {
        "index": 0,
        "size": 10,
        "ascOrDesc": "DESC",
        "queryDto":{
          "online": null,
          "userId": null,
          //博客类型
          "blogType": null,
          // 是否精华
          "isEssence": null,
          "isTop": null,
          "tagId": null,
          "kw": null
        },
        "properties": ["update_time"]
      },
      //其它数据
      otherData: {
        source: "picture",
        userUid: "uid00000000000000000000000000000000",
        adminUid: "uid00000000000000000000000000000000",
        projectName: "blog",
        sortName: "admin",
        token: getToken(),
      },
      contentSortUid: "8c767391edb3ae78418fb43697857f9e", //头像相册分类得uid
      uploadPictureHost: process.env.PICTURE_API + "/file/pictures",
      photoVisible: false,
      checkedPictureUrlList: [], //选择的图片url
      checkedFileUids: "", //选择的图片uid,逗号分隔
      icon: false, //控制删除图标的显示
      interval: null, //定义触发器
      rules: {
        // titlePicUids: [
        //   {
        //     required: true,
        //     validator: validatefile,
        //     message: "标题图不能为空",
        //     trigger: "blur",
        //   },
        // ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        typeId: [
          { required: true, message: "分类不能为空", trigger: "blur" },
        ],
        tagIdList: [
          {
            required: true,
            validator: validateTags,
            message: "标签不能为空",
            trigger: "blur",
            type: "array",
          },
        ],
        isEssence: [
          { required: true, message: "推荐等级不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "推荐等级只能为自然数" },
        ],
        online: [
          { required: true, message: "发布字段不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "发布字段只能为自然数" },
        ],
        isOriginal: [
          { required: true, message: "原创字段不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "原创字段只能为自然数" },
        ],
        startComment: [
          { required: true, message: "网站评论不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "网站评论只能为自然数" },
        ],
        blogContent: [
          {
            required: true,
            validator: validateContent,
            message: "博客内容不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    if (this.dialogFormVisible == false) {
      clearInterval(this.interval);
    }
    // 获取标签列表
    // this.tagList()
    // 获取博客分类
    this.blogTypeList()
    //获取博客列表
    this.blogList();
  },
  mounted() {
    // // 获取标签列表
    // this.tagList()
    // // 获取博客分类
    // this.blogTypeList()
  },
  methods: {
    handleAvatar(file) {
      this.form.pic = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess(res, file) {
      this.form.pic = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    async blogTypeList() {
       getBlogSortList().then((res) => {
        let result = res.data
        if(result.code === 200)
          this.blogTypes = result.data.result || []
        else
          alert(result.msg)
      });
    },
    async tagList() {
       await getTagList().then((res) => {
        let result = res.data
        if(result.code === 200)
          this.blogTagList = result.data.result || []
        else
          alert(result.msg)
      });
    },
    async blogList() {
      await this.tagList()
      this.Loading = true;
      var params = this.indexParam;
      params.index = this.currentPage;
      params.size = this.pageSize;
      getBlogList(params).then((res) => {
        if(res.data.code !== 200) {
          alert(res.data.msg)
          return
        }
        this.tableData = res.data.data.result
        for(var data of this.tableData){
          data.tagNameList = this.getTags(data.tagIds)
        }
        this.total = res.data.data.total
        this.total
        this.Loading = false;
      });
    },
    handleFind() {
      this.currentPage = 0
      this.blogList();
    },
    loadEditor() {
      this.$nextTick(function () {
        const options = {
          el: this.$refs.toastUIEditor,
          previewStyle: 'vertical',
          height: '600px',
          // initialEditType: 'wysiwyg',
          language: "zh-CN",
          initialValue: this.form.blogContent,
          hideModeSwitch: true,
        }
        this.editor = new Editor(options)
        // 删除默认监听事件
        this.editor.eventManager.removeEventHandler('addImageBlobHook')
        // 添加自定义监听事件
        this.editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
          // 此处填写自己的上传逻辑，url为上传后的图片地址
          this.editorUploadPic(blob, url => {
            callback(url)
          })
        })
      })
    },
    handleAdd() {
      if (Cookies.get('formBak')) {
        this.$confirm("还有上次未完成的博客编辑，是否继续编辑?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.form = Object.assign(this.form, JSON.parse(Cookies.get('formBak')));
            this.loadEditor();  //这里不加载的化，内容字段赋值不进去
          })
          .catch(() => {
            Cookies.remove("formBak")
          })
      }
      this.dialogFormVisible = true;
      this.loadEditor();
      this.formBak();
      this.title = "新增博客";
      this.isEditForm = false;
    },
    getBlogType(id){
      for (var blogType of this.blogTypes) {
        if(blogType.id === id)
          return blogType.name;
      }
    },
    getTags(ids){
      var tagNames = []
      var idStrs = ids.split(',')
      for(let str of idStrs){
        tagNames.push(this.getTag(parseInt(str)))
      }
      return tagNames
    },
    getTag(id){
      for (var tag of this.blogTagList) {
        if(tag.id === id)
          return tag.name;
      }
    },
    handleEdit(row) {
      this.$store.dispatch('app/setLoading', true);
      getContent(row.id).then((response) => {
        this.form = Object.assign(this.form, row);
        this.form.blogContent = response.data.data;
        this.form.tagIdList = [];
        if (row.tagIds) {
          var strs = row.tagIds.split(',')
          for(var str of strs){
            this.form.tagIdList.push(parseInt(str))
          }
        }
        this.title = "编辑博客";
        this.isEditForm = true;
        this.dialogFormVisible = true;
        this.loadEditor();
        this.$store.dispatch('app/setLoading', false);
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将把博客删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch('app/setLoading', true);
          var params = [];
          params.push(row.id)
          deleteBlog(params).then((response) => {
            this.$message({
              type: "success",
              message: response.data,
            });
            this.blogList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDeleteBatch() {
      if (this.multipleSelection <= 0) {
        this.$notify({
            title: '错误：',
            message: "请先选中需要删除的文章！",
            type: 'error'
          });
        return;
      }
      this.$confirm("此操作将把选中文章删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = [];
          for(var item of this.multipleSelection){
            params.push(item.id)
          }
          this.$store.dispatch('app/setLoading', true);
          deleteBatchBlog(params).then((response) => {
            this.$message({
              type: "success",
              message: response.data,
            });
            this.blogList();
          });
        })
        .catch(() => {
          this.$notify({
            title: '温馨提示：',
            message: "已取消删除！",
            type: 'info'
          });
        });
    },
    handleUpload() {
      this.localUploadVisible = true;
    },
    handleDownload() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          type: "error",
          message: "请先选中需要导出的文章！",
        });
        return;
      }
      let blogList = this.multipleSelection;
      for (let a = 0; a < blogList.length; a++) {
        getContent(blogList[a].uid).then((response) => {
          let viewerText = response.data;
          this.$commonUtil.downloadMarkdownFile(blogList[a].title, viewerText);

        });
      }
    },
    gotoBlogInfo(row) {
      window.open(this.VUE_APP_WEB_URL + "/article/" + row.uid);
    },
    submitPictureUpload() {
      this.$refs.uploadPicture.submit();
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.blogList();
    },
    // 改变多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    beforeHandleDialogClose() {
      this.$confirm("是否关闭文章编辑窗口", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.handleDialogClose();
        })
        .catch(() => {
          this.$notify({
            title: '温馨提示：',
            message: "已取消关闭",
            type: 'info'
          });
        });
    },

    //关闭dialog之前的处理
    handleDialogClose() {
      this.form = {
        id: null,
        title: null,
        pic: null,
        userId: null,
        typeId: null,
        tagIdList: [],
        isEssence: null,
        isTop: null,
        online: null,
        isOriginal: null,
        startComment: null,
        author: null,
        articlesPart: null,
        shortContext: null,
        blogContent: null
      };
      clearInterval(this.interval);
      this.dialogFormVisible = false;
    },
    // //弹出选择图片框
    // choosePhoto() {
    //   this.photoVisible = true;
    // },
    //关闭动态图片选择框
    cancelModel() {
      this.photoVisible = false;
    },
    getChooseData(data) {
      this.photoVisible = false;
      this.checkedFileUids = data.checkedFileUids;
      this.checkedPictureUrlList = data.checkedPictureUrlList;
      if (this.checkedPictureUrlList.length >= 1) {
        this.form.titlePicUids = this.checkedFileUids; //字符串逗号分隔
        this.form.titlePicUrlList = this.checkedPictureUrlList; //数组
      }
    },
    deletePhoto() {
      // this.form.titlePicUrlList = null;
      // this.form.titlePicUids = "";
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.tagIdList.length > 3) {
            this.$notify({
              title: "警告",
              message: "标签不能超过3个！",
              type: "warning",
            });
            return;
          }
          this.form.blogContent = this.editor.getMarkdown().toString(); //获取Editor中的内容
          this.form.tagIds = this.form.tagIdList.join(",");
          if (this.isEditForm) {
            //编辑
            this.$store.dispatch('app/setLoading', true);
            editBlog(this.form).then((response) => {
              this.$notify({
                title: "成功",
                message: response.data,
                type: "success",
              });
              this.handleDialogClose();
              this.blogList();
            });
          } else {
            //新增
            this.$store.dispatch('app/setLoading', true);
            addBlog(this.form).then((response) => {
              this.$notify({
                title: "成功",
                message: response.data,
                type: "success",
              });
              this.handleDialogClose();
              this.blogList();
              Cookies.remove("formBak")
            });
          }
        }
      });
    },
    /**
 * 编辑器中上传图片至服务器
 */
    editorUploadPic(file, callback) {
      //压缩文件
      this.$elUploadBeforeUpload(file).then(data => {
        var formData = new FormData();
        formData.append("file", data);
        formData.append("userUid", this.$store.getters.userUid);
        formData.append("sortName", "admin");
        //上传图片file
        this.$store.dispatch('app/setLoading', true);
        uploadFile(formData).then((response) => {
          let picture = {};
          picture.fileUid = response.data.uid;
          picture.pictureSortUid = this.contentSortUid;
          picture.picName = response.data.picName;
          //添加到分类中，添加到数据库
          callback(response.data.data)
          this.$notify({
            title: "成功",
            message: "上传成功！",
            type: "success",
          });
        });
      })
      // this.editor.toastuiEditor.invoke("getMarkdown");

    },
    //备份form表单
    formBak() {
      this.interval = setInterval(() => {
        if ((this.form.title != null && this.form.title != '') || (this.editor.getMarkdown() != null && this.editor.getMarkdown() != '')) {
          //存放到cookie中，半分钟自动保存一次
          this.form.blogContent = this.editor.getMarkdown(); //获取Editor中的内容
          Cookies.set("formBak", this.form)
        }
      }, 1000 * 60 * 0.5)
    }
  }
};
</script>

<style>
.imgBody {
  width: 195px;
  height: 105px;
  border: solid 2px #ffffff;
  float: left;
  position: relative;
}
.inputClass {
  position: absolute;
  z-index: 999;
}

.uploadImgBody {
  width: 195px;
  height: 105px;
  border: dashed 1px #c0c0c0;
  float: left;
  position: relative;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 195px;
  height: 105px;
  line-height: 105px;
}
.upload-demo {
  margin-top: 50px;
}
.tipBox {
  margin-bottom: 30px;
}
.tip {
  font-size: 14px;
  font-weight: bold;
  color: #808080;
}
.tipItem {
  line-height: 22px;
  color: #a9a9a9;
}
</style>
